package com.jdjw.modules.thirdpost.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdjw.common.ResponseResult;
import com.jdjw.modules.thirdpost.mapper.BusWarningResultMapper;
import com.jdjw.modules.thirdpost.param.BusWarningResultParam;
import com.jdjw.modules.thirdpost.param.JdWangShang;
import com.jdjw.modules.thirdpost.param.ThirdPostInParm;
import com.jdjw.modules.thirdpost.result.BusProcureApply;
import com.jdjw.modules.thirdpost.result.BusWarningResult;
import com.jdjw.utils.CommonUtil;
import com.jdjw.utils.ConstantUtil;
import com.jdjw.utils.DateUtil;
import com.jdjw.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 项目全流程——预警表 服务实现类
 * </p>
 *
 * @author fq
 * @since 2021-08-13
 */
@Slf4j
@Service
public class BusWarningResultServiceImpl extends ServiceImpl<BusWarningResultMapper, BusWarningResult> implements IService<BusWarningResult> {

    @Autowired
    static BusWarningResultMapper busWarningResultMapper;

    @Autowired
    static ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl;

    @Resource
    public void setThirdPostExceptionServiceImpl(ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl) {
        BusWarningResultServiceImpl.thirdPostExceptionServiceImpl = thirdPostExceptionServiceImpl;
    }

    @Resource
    public void setBusWarningResultMapper(BusWarningResultMapper busWarningResultMapper) {
        BusWarningResultServiceImpl.busWarningResultMapper = busWarningResultMapper;
    }


    public static void doPostSzJiandeersan(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 23;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 23;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 23;
        }
        try {
            //查询
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("deal_type", "2");
            if (StringUtils.isNotBlank(thirdPostInParm.getStartTime())) {
                queryWrapper.ge("create_time", thirdPostInParm.getStartTime());
            } else if (StringUtils.isNotBlank(thirdPostInParm.getEndTime())) {
                queryWrapper.le("create_time", thirdPostInParm.getEndTime());
            }
            List<BusWarningResult> list = busWarningResultMapper.selectList(queryWrapper);
            if (list == null || list.size() < 1) {
                log.info("项目全流程——预警表数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusWarningResult>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusWarningResult> obj : fgList) {
                    sendData((List<BusWarningResult>) obj, url);
                }
            } else {
                sendData(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendData(List<BusWarningResult> obj, String url) throws ParseException {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (BusWarningResult a : obj) {
            BusWarningResultParam param = new BusWarningResultParam();
            param.setId(a.getId());
            param.setBiz_id(a.getId());
//            param.setSsz();null
            param.setYjdx("无");
            param.setYjdxssdw("无");
            param.setYjdxzw("无");
//            param.setZwcj();null
            param.setYjsj(a.getCreateTime());
            param.setYjly(1);//村级工程
            param.setYjlx(2);//事件预警
//            param.setYjdj();
//            param.setYjgz();
            param.setYjms(a.getWarningName());
//            param.setYjhj();
            param.setSfclwc(3);//3
            param.setClsj(a.getDealTime());
            param.setCljg(a.getDealResult());
            param.setSfjz(1);
            param.setDel_flag(0);
            param.setCwh(a.getDept());
            param.setCwhxzqh(CommonUtil.addZeroForNum(a.getDeptId(), 16));

            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("项目全流程——预警表数据推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostSzJiandeersan", "项目全流程——预警表数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("项目全流程——预警表推送失败", result);
            }
        } else {
            log.info("项目全流程——预警表推送失败", "第三方返回空");
        }
    }


    /**
     * 网上公开
     */
    public static void doPostSzZyxzWangShang(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 21;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 21;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 21;
        }
        try {
            //查询
            List<BusProcureApply> list = busWarningResultMapper.selectListYu(thirdPostInParm);
            if (list == null || list.size() < 1) {
                log.info("网上公开数据库查询数据为0条");
                return;
            }
            if (list.size() > 3000) {
                Integer count = list.size() / 3000 + 1;
                Collection<Collection<BusProcureApply>> fgList = CommonUtil.subCollection(list, count);
                for (Collection<BusProcureApply> obj : fgList) {
                    sendDatatwo((List<BusProcureApply>) obj, url);
                }
            } else {
                sendDatatwo(list, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendDatatwo(List<BusProcureApply> obj, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        int b = 0;
        for (BusProcureApply a : obj) {
            JdWangShang param = new JdWangShang();
            if(StringUtils.isNotBlank(a.getCwhxzqh()) && a.getCwhxzqh().length()<16 && a.getCwhxzqh().length()>9){
                param.setCwhxzqh(CommonUtil.addZeroForNum(a.getCwhxzqh(), 16));
                param.setId(a.getId());
                param.setBiz_id(a.getId());
                param.setCwh(a.getCwh());
                param.setGkly(Integer.parseInt(a.getGkly()));
//                if ("1".equals(a.getGkly()) || "2".equals(a.getGkly())) {
//                    param.setGksx("全流程");
//                }
                param.setGksx("全流程");
                param.setGkny(datestr(a.getCreateDate().toString()));
                if (StringUtils.isNotBlank(a.getYgkzl())) {
                    param.setYgkzl(Integer.parseInt(a.getYgkzl()));
                } else {
                    param.setYgkzl(0);
                }
                //暂时推0
                param.setQzdjl(0);
                //转化为json字符串
                String jsonStr = JSONObject.toJSONString(param);
                //转化为json对象
                list.add(JSONObject.parseObject(jsonStr));
                b++;
            }

        }
        System.out.println("---: "+b+list);
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("网上公开数据推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "BusCaigouhetong", "网上公开数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("网上公开推送失败", result);
            }
        } else {
            log.info("网上公开推送失败", "第三方返回空");
        }
    }


    public static String datestr(String str){
        String formatStr2 = null;
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
            Date date = sdf.parse(str);
            formatStr2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            return formatStr2;
        }catch (Exception e){
            e.printStackTrace();
            log.info("网上公开推送失败", "第三方返回空");
        }
        return formatStr2;
    }

}
